package com.example.finalhomework.weather

import android.content.Context
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.finalhomework.R
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

// 城市数据类，包含城市ID、城市代码和城市名称
data class City(val id: Int, val city_code: String, val city_name: String)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WeatherCityScreen(navController: NavController, weatherViewModel: WeatherViewModel = viewModel()) {

    var cities by remember { mutableStateOf(listOf<City>()) }   // 使用 remember 保存城市列表的状态
    var searchQuery by remember { mutableStateOf("") }  // 使用 remember 保存搜索查询的状态
    val context = LocalContext.current  // 获取当前上下文

    // 使用 LaunchedEffect 在组合项启动时加载城市数据
    LaunchedEffect(Unit) {
        Log.d("WeatherCityScreen", "Loading city data")
        cities = withContext(Dispatchers.IO) {
            // 从 raw 资源目录中读取城市代码文件
            val str = weatherViewModel.readFileFromRaw(context, R.raw.citycode)
            val gson = Gson()
            // 使用 Gson 解析 JSON 数据
            val CityType = object : com.google.gson.reflect.TypeToken<List<City>>() {}.type
            val allCities: List<City> = gson.fromJson(str, CityType)
            Log.d("WeatherCityScreen", "City data loaded: ${allCities.size} cities")
            allCities.filter { it.city_code.isNotEmpty() }  // 过滤掉 city_code 为空的城市
        }
    }

    // 布局列，用于包含搜索框和城市列表
    Column(modifier = Modifier.padding(16.dp)) {
        // 搜索框
        TextField(
            value = searchQuery,
            onValueChange = { searchQuery = it },
            label = { Text("Search City") }, // 搜索框标签
            leadingIcon = {
                Icon(
                    painter = painterResource(id = R.drawable.baseline_search),
                    contentDescription = "weather search",
                )
            },
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White, shape = RoundedCornerShape(8.dp))
                .border(1.dp, Color.Black, shape = RoundedCornerShape(8.dp)),
            colors = TextFieldDefaults.textFieldColors(
                containerColor = Color.White
            )
        )

        Spacer(modifier = Modifier.height(16.dp))

        // 根据搜索查询过滤城市列表
        val filteredCities = cities.filter { it.city_name.contains(searchQuery, ignoreCase = true) }
        Log.d("WeatherCityScreen", "Filtered cities: ${filteredCities.size}")

        // 使用 LazyColumn 显示过滤后的城市列表
        LazyColumn(modifier = Modifier.padding(16.dp)) {
            items(filteredCities) { city ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(8.dp)
                        .height(50.dp)
                        .clickable {
                            Log.d("WeatherCityScreen", "City clicked: ${city.city_name}")
                            // 点击城市项时导航到天气详情页面
                            navController.navigate("weather/${city.city_code}")
                        },
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        painter = painterResource(id = R.drawable.icons8_cat_128),
                        contentDescription = null,
                        modifier = Modifier.size(20.dp),
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = city.city_name, modifier = Modifier.weight(1f))
                    Icon(
                        painter = painterResource(id = R.drawable.baseline_arrow_forward),
                        contentDescription = null,
                        modifier = Modifier.size(14.dp),
                        tint = Color.Gray
                    )
                }
                Box(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Divider(
                        color = Color.LightGray.copy(alpha = 0.5f), // 设置颜色
                        thickness = 1.dp, // 设置厚度
                        modifier = Modifier
                            .fillMaxWidth(1f)
                            .align(Alignment.Center) // 居中显示
                    )
                }
            }
        }
    }
}